#include "stdafx.h"

#include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>

#include "windows.h"
#include <vector>
#define __T(x)      L ## x 


HANDLE hPort;

int openCom(const char* port)
{
	char fileNameString[5];
	WCHAR    fileName[5];

	//Open Connection
	strcpy(fileNameString, "COM");
	strcat(fileNameString,port);
	MultiByteToWideChar( 0,0, fileNameString, 5, fileName, 5);
	if (INVALID_HANDLE_VALUE==(hPort=CreateFile(fileName,GENERIC_ALL,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0)))
    { return(GetLastError()); }

	//Setup Params
	DCB portDcb;
	memset(&portDcb,0,sizeof(portDcb)); portDcb.DCBlength=sizeof(portDcb);
	if (!(GetCommState(hPort,&portDcb))) { return(GetLastError()); }
	portDcb.BaudRate=38400;
	portDcb.ByteSize=8;
	portDcb.Parity=0;
	portDcb.StopBits=1;
	if (!(SetCommState(hPort,&portDcb))) { return(GetLastError()); }
	//setup timeouts
	 COMMTIMEOUTS commTimeOuts;
	 commTimeOuts.ReadIntervalTimeout=5;
     commTimeOuts.ReadTotalTimeoutMultiplier=5;
     commTimeOuts.ReadTotalTimeoutConstant=5;
     commTimeOuts.WriteTotalTimeoutMultiplier=10;
     commTimeOuts.WriteTotalTimeoutConstant=100;
	SetCommTimeouts(hPort,&commTimeOuts);


	return 0;
}


int closeCom()
{
	 if (hPort!=INVALID_HANDLE_VALUE) { CloseHandle(hPort); hPort=INVALID_HANDLE_VALUE; }
	 return 0;
}

void quit(int num,char* error)
{
	if (num!=0)
	{
		printf("\n\nError code:%d : %s", num, error);
	}
	//to prevent console close
	/*for debug*/ printf("\n\nPress any key to exit");	char end;	scanf("%c", &end); 
	//goto end;
}


void fileToString(std::vector<char>*  g, char* fileName)
{
	 ifstream in(fileName, ios::in | ios::binary);

	if(!in) {
	quit(-1, "not able to open input file");
	}
  
	char temp [9] = "\0";
	int read = 0;
	g->resize(1);
	(*g)[0]='\0';
	DWORD pdwRead=1;
	
	while(!in.eof())
	{
		in.read(temp,8);
		g->resize(9+read);
		temp[in.gcount()]='\0';
		strcat(&(*g)[0],temp);
		read += in.gcount();
	}  
	in.close();
	//printf("\n\n%c|\n\n",(*g)[strlen(&(*g)[0])-2]);
}




int readOld(std::vector<char>*  g)
{
//check sizes of incoming strings for validity
//Check if port exists from previous init
printf("Read back\n");
	char toRead[9]="\0";
	int readLength=8;
	int read = 0;
	g->resize(1);
	(*g)[0]='\0';
	DWORD pdwRead=1;
	while(pdwRead >0)
	{
		if (!ReadFile(hPort,&toRead,readLength,&pdwRead,NULL)) return(GetLastError());
		if(pdwRead >0)
		{	
			g->resize(9+read);
			toRead[pdwRead]='\0';
			strcat(&(*g)[0],toRead);
			read += pdwRead;
		}
	}
	return 0;
}


int send(char* data)
{
//check sizes of incoming strings for validity
//Check if port exists from previous init
	
	DWORD dwWritten=0;
	int written = 0;
	int index=0;
	printf("Sending\n");
	//printf("\n\n|%c|\n\n",toWrite[strlen(toWrite)-1]);
	while(writeLength != 0)
	{
		writeLength-=3;


		if (!WriteFile(hPort,&toWrite[index] ,3,&dwWritten,NULL)) return(-8);
		if (dwWritten<currentWrite) return(-9);
		index += currentWrite;
		Sleep(1000);
	}
	printf("Done Sending\n");
	return 0;
}


int _tmain(int argc, _TCHAR* argv[])
{
	char * port = "6";
	std::vector<char> readBuf;


	//Open and setup Com Connection
	/*for debug*/ printf("PC:Connecting to FPGA on COM%s...",port);
	if(openCom(port) !=0)
	{ printf("Could not connect\n"); }
	else{
		 printf("Connected\n"); 

	if(write("545") !=0)
		{ return(GetLastError()); }

		 if(read(&readBuf) !=0){ return(GetLastError()); }
			printf("Read:%s\n",&readBuf[0]);

		//CloseCom
		/*for debug*/ printf("PC:Closing connection\n");
		if(closeCom() !=0)
		{ return(GetLastError()); }

	}
	
	return quit(0,"");		//prompts and waits for key press to quit

}
